<template>
  <view class="container">
    <view class="navigate">
      <view class="doing" :class="{active:activeTab === 'doing'}" @click="switchTab('doing')">
        进行中
      </view>
      <view class="hx">|</view>
      <text class="done" :class="{active:activeTab === 'done'}" @click="switchTab('done')">
        已结束
      </text>
    </view>

    <!-- 进行中列表 -->
    <view v-if="activeTab === 'doing'">
      <view class="item_doing" v-for="(item,index) in ongoingList" :key="index||item.activityId">
        <view class="pic_container">
          <!-- 直接用接口返回的 activityImg（需是完整可访问 URL） -->
          <!-- <img src="/sta" alt="" class="image" /> -->
		  <image class="image" src="/static/1.png"></image>
          <view class="concret_thing" >
            <text>{{ item.activityName }}</text>
          </view>
          <view class="bm" style="margin-top: 5px;">
            已报名：{{ item.enrollment}}
            <button type="primary">进行中</button>
          </view>
        </view>
        <view class="border_line"></view>
        <!-- 地图导航卡片 -->
        <view class="card" @click="openMap(item)">
          <view class="card-content">
            <image src="/static/map-icon.png" class="map-icon"></image>
            <text class="card-title">{{item.parsedAddress}}</text>
            <text class="location-detail">{{ item.startDate || '2025-01-01' }} - 
              {{ item.endDate || '2025-12-31' }}</text>
          </view>
          <text class="map_nav">地图导航</text>
        </view>
      </view>
      <view class="end" v-if="ongoingList.length > 0">
        暂时没有更多了
      </view>
      <view class="no-data" v-else>
        暂无进行中的活动
      </view>
    </view>
    <!-- 已结束列表 -->
    <view v-if="activeTab === 'done'">
      <view class="item_done" v-for="(item,index) in ondoneList" :key="index">
        <view class="pic_container">
          <!-- 同样直接用接口返回的 activityImg -->
          <img :src="item.activityImg" alt="" class="image"/> 
          <view class="concret_thing" >
            <text>{{ item.title }}</text>
          </view>
          <view class="bm" style="margin-top: 5px;">
            已报名：{{ item.joined}}
            <button>已结束</button>
          </view>
        </view>
      </view> 
      <view class="end" v-if="ondoneList.length > 0">
        暂时没有更多了
      </view>
      <view class="no-data" v-else>
        暂无已结束活动
      </view>
    </view>
    <!-- 底部导航 -->
   <!-- <view class="bottom-tabbar"> -->
      <!-- <view class="tabbar-item" @click="goHome">
        <uni-icons type="home" size="24"></uni-icons>
        <view>首页</view>
      </view>
      <view class="tabbar-item" @click="goStudyRecord">
        <uni-icons type="wallet-filled" size="24"></uni-icons>
        <view>学习记录</view>
      </view>
      <view class="tabbar-item" @click="goMy">
        <uni-icons type="auth" size="24"></uni-icons>
        <view>我的</view>
      </view>
    </view> -->
  </view>
</template>

<script>
// import { getActivityList } from '/api/activity.js';
import { userTraining } from '@/api/sign.js'
import {userList} from '@/api/sign.js'
import {selectOneById} from '@/api/activity.js'
export default {
  data() {
    return {
      activeTab: 'doing', 
      ongoingList: [],
      ondoneList: [],
	  userId:'',
	  activityId:'',
	  activityForm:[],
    };
  },
  async onLoad() {
	  this.loadCachedData();
  },
  methods: {
	  async loadCachedData() {
	      try {
	        const res = await uni.getStorage({ key: 'user' });
			this.userId=res.data.userId;
			console.log("用户ID"+res.data.userId)
			
			const res1=await userTraining(res.data.userId);
			this.activityId=res1.data[0].activityId
			console.log("活动数据"+res1.data[0].activityId)
			
			const res2=await selectOneById(this.activityId,this.userId)
			this.ongoingList=res2.data
			console.log(this.ongoingList)
			// const info=await userList(this.userId,0)
			 // 处理数据格式
			this.ongoingList = res2.data ? 
			          (Array.isArray(res2.data) ? res2.data : [res2.data]) : [];
			        
			this.ongoingList.forEach((item, index) => {
			console.log(`第 ${index + 1} 个 item 的 trainingInfo:`, item.trainingInfo);
		      if (item.trainingInfo) {
			           try {
			             // 清理特殊字符
			             const cleanedTrainingInfo = item.trainingInfo
			               .replace(/\n/g, "")
			               .replace(/\s+/g, " ");
			       
			             // 解析为数组
			             const trainingInfoArr = JSON.parse(cleanedTrainingInfo);
			             if (Array.isArray(trainingInfoArr) && trainingInfoArr.length > 0) {
			               console.log('解析后的 trainingInfo 对象:', trainingInfoArr[0]);
			               item.parsedAddress = trainingInfoArr[0].address;
			               // 提取经纬度
			               item.parsedLatitude = trainingInfoArr[0].latitude;
			               item.parsedLongitude = trainingInfoArr[0].longitude;
			             } else {
			               console.error("trainingInfo 是数组但为空");
			               item.parsedAddress = "地址解析失败（数组为空）";
			               item.parsedLatitude = 0; // 默认值
			               item.parsedLongitude = 0; // 默认值
			             }
			           } catch (error) {
			             console.error("解析 trainingInfo 失败:", error);
			             item.parsedAddress = "地址解析失败";
			             item.parsedLatitude = 0; // 默认值
			             item.parsedLongitude = 0; // 默认值
			           }
			         } else {
			           console.warn("trainingInfo 为 null 或 undefined");
			           item.parsedAddress = "无地址信息";
			           item.parsedLatitude = 0; // 默认值
			           item.parsedLongitude = 0; // 默认值
			         }
			       });
	      } catch (err) {
	        console.error('读取缓存失败', err);
	      }
	    },
    goMy() {
      uni.navigateTo({ url: '/pages/my/my' });
    },
    goHome() {
      uni.navigateTo({ url: '/pages/main/main' });
    },
    goStudyRecord() {
      uni.navigateTo({ url: '/pages/record/record' });
    },
    switchTab(tab) {
      this.activeTab = tab;
    },
    openMap(item) {
      // 使用解析后的经纬度
      const latitude = item.parsedLatitude ? parseFloat(item.parsedLatitude) : 0;
      const longitude = item.parsedLongitude ? parseFloat(item.parsedLongitude) : 0;
      const address = item.parsedAddress || "未知地址";
    
      if (latitude === 0 || longitude === 0) {
        uni.showToast({
          title: '经纬度信息缺失，无法导航',
          icon: 'none'
        });
        return;
      }
    
      uni.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: item.activityName || "活动地点",
        address: address,
        success: () => console.log('打开地图成功，地点:', address),
        fail: (err) => {
          console.log('打开地图失败:', err);
          uni.showToast({
            title: '打开地图失败，请检查是否安装了地图应用',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>


<style scoped>
.container{
  width: 100%;
  min-height: 100vh;
  background-color: #F0F0F0;
  /* padding-bottom: 20rpx; */
}
.navigate{
  width: 100%;
  height: 50px;
  /* border: 1px solid gainsboro; */
  display: flex;
  background-color: white;
  justify-content: space-around;
}
.navigate .hx{
  line-height: 50px;
  height: 35px;
  color:#EBEBEB
}
.navigate .doing{
  line-height: 50px;
  text-align: center;
  width: 50%;
}
.navigate .doing:active{
  border-bottom: 1px solid #FF7144;
}
.navigate .done:active{
  border-bottom: 1px solid #FF7144;
}
.navigate .done{
  line-height: 50px;	
  text-align: center;
  width: 50%;
}
.item_doing{
  overflow: hidden;
  border-radius: 20px;
  width: 90%;
  height: 190px;
  background-color: white;
  margin-top: 10px;
  margin-left: 18px;
}
.item_doing .pic_container{
  height: 100px;
}
.item_doing .image{
  width: 80px;
  height: 80px;
  margin-top: 10px;
  margin-left: 5px;
  margin-right: 10px;
  float:left;
}
.item_doing .concret_thing{
  margin-top: 10px;
  font-weight: bold;font-size: 15px;
}
.item_doing .bm{
  float: left;
}
.item_doing button{
  float: right;
  font-size: 14px;
  width: 70px;
  height: 30px;
  line-height: 30px;
  margin-left: 70px;
  margin-top: -5px;
  font-weight: 500;
}
.item_doing .border_line{
  border-top: 1px solid #EBEBEB;
  width: 90%;
  margin-left: 20px;
}
.item_done{
  overflow: hidden;
  border-radius: 20px;
  width: 90%;
  height: 110px;
  background-color: white;
  margin-top: 10px;
  margin-left: 18px;
}
.item_done .pic_container{
  height: 100px;
}
.item_done .image{
  width: 80px;
  height: 80px;
  margin-top: 10px;
  margin-left: 5px;
  margin-right: 10px;
  float:left;
}
.item_done .concret_thing{
  margin-top: 10px;
  font-weight: bold;font-size: 15px;
}
.item_done .bm{
  float: left;
}
.item_done button{
  float: right;
  font-size: 14px;
  width: 70px;
  height: 30px;
  line-height: 30px;
  margin-left: 70px;
  margin-top: -5px;
  font-weight: 500;
  background-color: grey;
}
.item_done .border_line{
  border-top: 1px solid #EBEBEB;
  width: 90%;
  margin-left: 20px;
}

/* .card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
} */
.card .map_nav{
  float: right;
  margin-top: 50rpx;
  margin-right: 10rpx;
  color: gold;
}
.card-content {
  float: left;
  margin-left: 10rpx;
  margin-top: 10rpx;
  align-items: center;
  
}

.map-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

.card-title {
  font-size: 26rpx;
  color: #BDBDBD;
}

.location-detail {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-top: 10rpx;
}

.event-details {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
}

.detail-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  width: 150rpx;
}

.detail-value {
  font-size: 28rpx;
  color: #666;
  flex: 1;
}

.end{
  text-align: center;
  padding: 20rpx 0;
  color:#B0B0B0;
  background-color: #F0F0F0;
}
.bottom-tabbar {
  display: flex;
  border-top: 1px solid #f2f2f2;
}

.tabbar-item {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #333;
}
.go-end {
  white-space: nowrap;
  padding: 5px 12px;
  background-color: #a5a09d;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  border: none;
}
</style>